public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        if (array == null) {
            array = new Node[DEFAULT_SIZE];
        }
        // write code here
        int index = key % array.length;
        Node cur = array[index];

        Node node = new Node(key, value);
        Node parent = null;//记录上一个 节点
        if (cur == null) {
            array[index] = node;
            size++;
            if (loadFactor() >= LOAD_FACTOR) {//当大于等于LOAD_FACTOR时重新哈希
                resize();
            }
            return;
        }
        while (cur != null) {
            if (cur.key == key) {//遇到重复key 更新value
                cur.value = value;
                return;
            }
            parent = cur;
            cur = cur.next;
        }
        //头插法,不过这样显得cur没用了
        /*node.next = array[index];
        array[index] = node;*/
        //尾插法
        parent.next = node;
        size++;
        if (loadFactor() >= LOAD_FACTOR) {//当大于等于LOAD_FACTOR时重新哈希
            resize();
        }
    }

    //重新哈希
    private void resize() {
        // write code here
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % newArray.length;
                //在这里头插法比较容易
                Node node = new Node(cur.key, cur.value);
                node.next = newArray[index];
                newArray[index] = node;

                cur = cur.next;
            }
        }

        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
    }


    public int get(int key) {
        // write code here
        if (array == null) {
            return -1;
        }
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
